package cn.stronglink.asset.module.assetmanage.puton.service;

import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.toolkit.IdWorker;

import cn.stronglink.asset.model.AssetRecord;
import cn.stronglink.asset.model.ItAsset;
import cn.stronglink.asset.model.ItAssetExtPosition;
import cn.stronglink.asset.model.PutOn;
import cn.stronglink.asset.model.PutOnDetail;
import cn.stronglink.asset.model.RfidState;
import cn.stronglink.asset.model.TRoom;
import cn.stronglink.asset.module.assetRecord.mapper.AssetRecordMapper;
import cn.stronglink.asset.module.assetmanage.itasset.mapper.ItassetExtPositionMapper;
import cn.stronglink.asset.module.assetmanage.itasset.mapper.ItassetMapper;
import cn.stronglink.asset.module.assetmanage.itasset.vo.ItAssetVo;
import cn.stronglink.asset.module.assetmanage.puton.mapper.PutOnMapper;
import cn.stronglink.asset.module.basicdata.tRoom.mapper.TRoomMapper;
import cn.stronglink.asset.module.rfidState.mapper.RfidStateMapper;
import cn.stronglink.asset.terminal.unicom.param.UpdateAssetParam;
import cn.stronglink.suite.core.config.Resources;
import cn.stronglink.suite.core.exception.BusinessException;
import cn.stronglink.suite.core.util.PropertiesUtil;
import cn.stronglink.suite.core.util.WebUtil;

@Service
@Transactional(rollbackFor=Exception.class) 
public class PutOnService {

	@Autowired
	private PutOnMapper putOnMapper;
	@Autowired
	private ItassetMapper itassetMapper;
	@Autowired
	private ItassetExtPositionMapper itassetExtPositionMapper;
	@Autowired
	private TRoomMapper tRoomMapper;
	@Autowired
	private RfidStateMapper rfidStateMapper;
	@Autowired
	private AssetRecordMapper assetRecordMapper;

	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public Page<PutOn> queryPutOnList(Page<PutOn> page, Map<String, Object> params) {
		
		// 首先查询出所有上架单
		List<PutOn> putOnList =putOnMapper.queryPutOnList(page,params);
		
		//再根据每个上架单号查询出所有明细，并且把每个明细的设备型号，所在机柜拼接存放到上架单中。
		for(int i=0;i<putOnList.size();i++){
			PutOn puton=putOnList.get(i);
			Long putOnId=puton.getId();
			String modelNames="";
			String rackNames="";
			List<PutOnDetail> putOnDetailList =putOnMapper.queryPutOnDetailByParentId(putOnId);
			if(putOnDetailList!=null&&putOnDetailList.size()>0){
				if(putOnDetailList.size()>1){
					for(PutOnDetail putOnDetail:putOnDetailList){
						modelNames+=putOnDetail.getModelName()+"/";
						rackNames+=putOnDetail.getRackName()+"/";
					}
				}else{
					for(PutOnDetail putOnDetail:putOnDetailList){
						modelNames+=putOnDetail.getModelName();
						rackNames+=putOnDetail.getRackName();
					}
				}
			}
			puton.setModelNames(modelNames);
			puton.setRackNames(rackNames);
		}
		page.setRecords(putOnList);
		return page;	
	}
	
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public PutOn queryPutOnDetailList(Long id) {
		return putOnMapper.queryPutOnById(id);
	}

	public void remove(Long id) {
		try {
			putOnMapper.removeDetailByPutOnId(id);
			putOnMapper.remove(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void edit(PutOn putOn) {
		try {
			putOnMapper.updatePutOn(putOn);
			for(PutOnDetail detail :putOn.getDetailList()){
				if (detail.getId() == null) {
					detail.setId(IdWorker.getId());
					detail.setStatus(3);
					detail.setAssetId(Long.parseLong(detail.getAssetId_()));
					detail.setCreateBy(WebUtil.getCurrentUser());
					detail.setCreateTime(new Date());
					putOnMapper.insertPutOnDetail(detail);		
				}else{
					detail.setUpdateTime(new Date());
					detail.setUpdateBy(WebUtil.getCurrentUser());
					putOnMapper.updatePutOnDetail(detail);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	public int create(PutOn putOn) {
		putOn.setType(1);
		putOn.setStatus(1);
		putOn.setCreateBy(WebUtil.getCurrentUser());
		putOn.setCreateTime(new Date());
		int count =putOnMapper.insertPutOn(putOn);	
		if(putOn.getDetailList()!=null&&putOn.getDetailList().size()>0){
			for(PutOnDetail detail:putOn.getDetailList()){
				detail.setId(IdWorker.getId());
				detail.setStatus(2);
				detail.setAssetId(Long.parseLong(detail.getAssetId_()));
				detail.setPutOnId(putOn.getId());
				detail.setCreateBy(WebUtil.getCurrentUser());
				detail.setCreateTime(new Date());
				putOnMapper.insertPutOnDetail(detail);	
			}
		}
		return count;
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public List<PutOn> getPutUpList(Long userId) {
		// 首先查询出所有上架单
		List<PutOn> list =putOnMapper.getPutUpList(userId);		
		//再根据每个上架单号查询出所有明细，并且把每个明细的设备型号，所在机柜拼接存放到上架单中。
		if(list!=null&&list.size()>0){
			for(int i=0;i<list.size();i++){
				PutOn puton=list.get(i);			
				List<ItAssetVo> dList =itassetMapper.qryPutOnDetailVo(puton.getId());
				if(dList!=null&&dList.size()>0){
					puton.setdList(dList);
					puton.setCount(dList.size());
				}				
			}
		}
		return list;	
	}

	public void editShelfUp(PutOn putOn) throws Exception {
		putOn.setStatus(3);
		putOn.setUpdateBy(WebUtil.getCurrentUser());
		putOn.setUpdateTime(new Date());
		PutOn p =putOnMapper.queryPutOnById(putOn.getId());
		//更新上架单为已完成
		putOnMapper.updatePutOn(putOn);
		if(putOn.getDetailList()!=null&&putOn.getDetailList().size()>0){
//			for(PutOnDetail dObj:putOn.getDetailList()){
//				//判断要上架的设备是否有重复的U位
//				int uHeight = dObj.getuHeight();
//				if(uHeight==0){
//					uHeight =1;
//				}
//				int endU = dObj.getStartU()+uHeight-1;
//				
//				
//				
//				
//			}
			
		//	List<UpdateAssetParam> paramList = new ArrayList<UpdateAssetParam>();
			for(PutOnDetail detail:putOn.getDetailList()){
				detail.setStatus(1);
				detail.setId(Long.parseLong(detail.getDetailId()));
				detail.setUpdateBy(putOn.getUpdateBy());
				detail.setUpdateTime(new Date());
				putOnMapper.updatePutOnDetail(detail);
				//更新资产表状态为已上架，并且更新资产明细表中 机柜Id 起始U 结束U
				ItAsset asset = new ItAsset();
				asset.setId(Long.parseLong(detail.getAssetId_()));
				asset.setStatus(2);
				itassetMapper.updateItAsset(asset);
				int uHeight = detail.getuHeight();
				if(uHeight==0){
					uHeight =1;
				}
				ItAssetExtPosition posi= new ItAssetExtPosition();
				posi.setRoomId(p.getRoomId());
				if(detail.getAssetId_()!=null&&!detail.getAssetId_().isEmpty()) {
					posi.setAssetId(Long.parseLong(detail.getAssetId_()));
				}
				if(detail.getRackId()!=null&&!detail.getRackId().isEmpty()) {
					posi.setRackId(Long.parseLong(detail.getRackId()));
				}
				if(detail.getStartU()!=null) {
					posi.setEnd(detail.getStartU()+uHeight-1);
				}
				if(detail.getStartU()!=null) {
					posi.setStart(detail.getStartU());
				}
				itassetExtPositionMapper.updateItAssetExtPosition(posi);		
				 //插入资产生命周期表记录
				 AssetRecord re = new AssetRecord();
				 re.setId(IdWorker.getId());
				 re.setAssetId(Long.parseLong(detail.getAssetId_()));
				 re.setType(2);
				 re.setCreateBy(WebUtil.getCurrentUser());
				 re.setCreateTime(new Date());
				 assetRecordMapper.create(re);
				
				//查询该机柜下所有被占的U位		
//				List<ItAssetExtPosition> list=itassetExtPositionMapper.qryAssetExtPositionByRackId(Long.parseLong(detail.getRackId()));
//				if(list!=null&&list.size()>0){
//					for(ItAssetExtPosition data:list){
//						//录入范围 在 已存在范围 表示被占用，或者的 情况下   已存在的范围在录入范围也表示被占用
//						if(((data.getStart()<=detail.getStartU()&&detail.getStartU()<=data.getEnd())||((data.getStart()<=posi.getEnd()&&posi.getEnd()<=data.getEnd())))
//							||((detail.getStartU()<=data.getStart()&&data.getStart()<=detail.getEndU())||(posi.getStart()<=data.getEnd()&&data.getEnd()<=posi.getEnd()))){
//							//占用
//							throw new BusinessException(Resources.getMessage("UHEIGHT_BE_OCCUPIED"));
//						}
//					}
//				}
				//TRoom room= tRoomMapper.qryRoomNameById(detail.getRoomId());
				
//				UpdateAssetParam param = new UpdateAssetParam();
//				param.setCmdbId(Long.parseLong(detail.getAssetId_()));
//				param.setRfId(detail.getRfidNo());
//				param.setStartu(detail.getStartU());
//				param.setCountu(uHeight);
//				param.setRackName(rackInfo.getAssetName());
//				param.setRoomName(room.getName());
//				paramList.add(param);
				
			}
			
//			String jsonParam = JSON.toJSONString(paramList);
//			System.out.println(jsonParam+"web上架数据传给uop的数据");
//			CloseableHttpClient httpclient = HttpClients.createDefault();
//			HttpUriRequest sync = RequestBuilder.post()
//					.setUri(new URI(PropertiesUtil.getString("visitUrl")+"resConfirm"))
//					.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8")
//					.addParameter("value", jsonParam)
//					.build();
//			    CloseableHttpResponse response = httpclient.execute(sync);
//				HttpEntity result = response.getEntity();
//			try {
//				String msg = EntityUtils.toString(result);
//				System.out.println(msg+"-----------------------------------------------------");
//			} finally {
//				response.close();
//				httpclient.close();
//			}
		}
	}
	
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public Page<ItAssetVo> querAssetListByParam(Page<ItAssetVo> page,Map<String, Object> params) {
		page.setRecords(putOnMapper.querAssetListByParam(page,params));
		return page;
	}
	
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public List<PutOnDetail> qryPutOnDetailVo(Long id) {
		return putOnMapper.qryPutOnDetailVo(id);
	}

}
